import axios from 'axios'
import router from '../router/index'
import Vue from 'vue'
import store from '../store/index'
import { Message } from 'element-ui'

// axios.defaults.withCredentials = true;

Vue.prototype.$Message = Message;

import Cookies from 'js-cookie'

let token = ''
let cid = ''

class HttpRequest {
  constructor (baseUrl = baseURL) {
    this.baseUrl = baseUrl
    this.queue = {}
  }
  getInsideConfig (noToken) {
    if (noToken){
      // 登录等接口请求headers无需处理
      const config = {
        baseURL: this.baseUrl,
        headers: {
          'Content-Type': 'application/json; charset=UTF-8'
        }
      }
      return config
    } else {
      // 需要身份验证请求headers中加入token，cid
      if (!cid) {
        cid = Cookies.get('userId')
      }
      if (!token) {
        token = Cookies.get('token')
      }
      const config = {
        baseURL: this.baseUrl,
        headers: {
          'Content-Type': 'application/json; charset=UTF-8',
          'token': token,
          'cid': cid
        }
      }
      return config
    }
  }
  destroy (url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }
  interceptors (instance, url) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      // 添加全局的loading...

      if (!Object.keys(this.queue).length) {
        // Spin.show() // 不建议开启，因为界面不友好
      }
      this.queue[url] = true
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      // 登录成功后操作
      this.destroy(url)
      const { data } = res
      if (data.status === 1) {
        if (url.indexOf('admin/login') !== -1 ) {
          token = res.data.content.token
          cid = res.data.content.userInfo.id
        }
        return data.content
      } else {
        Vue.prototype.$Message.error(data.msg)
        return Promise.reject(data.msg)
      }
    }, error => {
      this.destroy(url)
      let errorInfo = error.response
      if (!errorInfo) {
        const { request: { statusText, status }, config } = JSON.parse(JSON.stringify(error))
        // errorInfo = {
        //   statusText,
        //   status,
        //   request: { responseURL: config.url }
        // }
      }
      if (error.response.status === 401) {
        clearUserCookiesAndToLogin()
        Vue.prototype.$Message.error('身份信息失效，请重新登录')
      }
      return Promise.reject(error)
    })
  }
  request (options) {

    // if (store.user.user)
    if (options.data) {
      Object.keys(options.data).forEach( item => {
        if ( (options.data[item] !== 0 && !options.data[item]) || ( options.data[item] instanceof Array && options.data[item].length === 0)  || ( options.data[item] instanceof Object && Object.keys(options.data[item]).length === 0) ) delete options.data[item]
      })
    }
    if (options.url.indexOf('loginOut') === -1) {
      const instance = axios.create()
      options = Object.assign(this.getInsideConfig(options.noToken), options)
      this.interceptors(instance, options.url)
      return instance(options)
    } else {
      clearUserCookiesAndToLogin()
    }
  }
}

// 请出管理员缓存信息并返回登录页面
export const clearUserCookiesAndToLogin = () => {

  Cookies.remove('token')
  Cookies.remove('accessList')
  Cookies.remove('userId')
  router.replace({
    path: '/login',
    query: {redirect: router.currentRoute.name}
  })
}

export default HttpRequest
